﻿using System;
using MVVMtutorialAdvanced.Web;
using Riba.MVVMSL;

namespace MVVMtutorialAdvanced
{
	public class AuthorDetails_VM : ViewModelBase
	{
		private readonly DomainServices.IDomainServiceBook _domainService;
		public RelayCommand CommandOk { get; private set; }

		private AuthorDTO _currentEntity;
		public AuthorDTO CurrentEntity
		{
			get { return _currentEntity; }
			set { SetPropertyValue(ref _currentEntity, value, () => CurrentEntity); }
		}

		public AuthorDetails_VM(DomainServices.IDomainServiceBook domainService)
		{
			_domainService = domainService;
			ExchangeDataAvailable += vm_ExchangeDataAvailable;
			ChildWindowClosed += AuthorDetails_VM_ChildWindowClosed;
			CommandOk = new RelayCommand(OnCommandOk);

			if (IsInDesignTool)
				CurrentEntity = new AuthorDTO { Id = 1, FirstName = "First", LastName = "Last" };
		}

		void AuthorDetails_VM_ChildWindowClosed(object sender, ChildWindowClosedEventArgs e)
		{
			_domainService.RejectChanges();  //Cancel not submitted changes
		}

		private void vm_ExchangeDataAvailable(object sender, ExchangeDataAvailableEventArgs e)
		{
			var data = ExchangeData as AuthorDTO;
			if (data == null)
				return;

			CurrentEntity = data;

			CommandOk.IsEnabled = true;
		}

		private void OnCommandOk(object handler)
		{
			if (CurrentEntity.HasValidationErrors)
				return;
			if (CurrentEntity.FirstName == null || CurrentEntity.LastName == null)
				return;

			if (CurrentEntity.Id > 0)
				_domainService.UpdateAuthor(CurrentEntity, UpdateOrInsertAuthorCompleted);
			else
				_domainService.InsertAuthor(CurrentEntity, UpdateOrInsertAuthorCompleted);
		}

		private void UpdateOrInsertAuthorCompleted(Exception exception)
		{
			if (exception != null)
			{
				RaiseShowMsgBox(new ShowMsgBoxEventArgs(exception.Message, "Fehler in UpdateOrInsertAuthorCompleted"));
				return;
			}

			if (Callback != null)
				Callback(this, CurrentEntity);

			RaiseCloseChildWindowView();
		}
	}
}
